<template>
  <view class="container">
    <view class="content">
      <cjx-upload
        v-model="imageDefine"
        :limit="6"
        @change="uploadChange"
        @passMaximumChange="passMaximumChange"
        @remove="onDelete"
        accept="xlsl/*,.xls,.xlsl,pdf/*,.pdf,docx/*,.docx"
      >
        <template #default>
          <view style="display: flex; width: 686rpx">
            <text
              :class="props.isrequired ? 'isrequired textClass' : 'textClass'"
              style="font-size: 32rpx"
            >
              {{ props.fileTitle }}
            </text>
            <span style="flex-grow: 1"></span>
            <image
              slot="icon"
              src="@/static/icon/plus-circle.svg"
              style="width: 40rpx; height: 40rpx"
            ></image>
          </view>
          <view style="color: #86909c; margin-top: 20rpx">
            {{ props.fileSubtitle }}
          </view>
        </template>
      </cjx-upload>
    </view>
    <!-- 自定义文件列表显示 -->
    <view v-if="imageDefine.length > 0" class="file-list">
      <view v-for="(file, index) in imageDefine" :key="index" class="file-item">
        <view class="file-info">
          <text class="file-name">{{ file.name || file.originalFilename }}</text>
          <text class="file-size">{{ formatFileSize(file.size) }}</text>
        </view>
        <i class="iconfont icon-cuowuguanbiquxiao" @click="handleDelete(file, index)"></i>
      </view>
    </view>
  </view>
</template>

<script setup>
import { defineEmits, defineProps, ref } from 'vue'
import { commonUpload } from '@/config'
import { getToken } from '@/utils/auth'
import {  detectFileTypeS } from '@/utils/fileTypeUtils'
const emit = defineEmits(['progress', 'getSuccessUrl', 'progress', 'success', 'fail', 'onDelete'])

const props = defineProps({
  // 文件扩展名限制
  fileExtname: {
    type: String,
    default: 'png,jpg,jpeg,doc,docx,pdf,xls,xlsx',
  },
  limit: {
    type: Number,
    default: 6,
  },
  // 媒体类型：image（图片）、file（文件）、mixed（混合）
  mediaType: {
    type: String,
    default: 'image',
    validator: (value) => ['image', 'file', 'mixed'].includes(value),
  },
  // 附件标题名称
  fileTitle: {
    type: String,
    default: '附件',
  },
  // 附件副标题名称
  fileSubtitle: {
    type: String,
    default: '',
  },
  // 附件是否必填
  isrequired: {
    type: Boolean,
    default: false,
  },
})

const imageDefine = ref([])
const uploadFileToServer = (file) => {
  // 注意：需要替换成你的实际上传接口地址
  const uploadUrl = commonUpload
  // 使用uniapp的上传文件API
  uni.uploadFile({
    url: uploadUrl, // 服务器上传接口地址
    filePath: file.tempFilePath, // 必须使用文件对象的tempFilePath
    name: 'file', // 服务器接收文件的参数名（需和后端约定）
    formData: {
      user: 'test',
    },
    header: {
      // 常见格式：Bearer + token（需和后端约定）
      Authorization: 'Bearer ' + getToken(),
    },
    success: (res) => {
      const result = JSON.parse(res.data)
      if (result.code === 200) {
        emit('getSuccessUrl', result.fileName)
      } else {
        uni.showToast({
          title: `上传失败：${result.message}`,
          icon: 'none',
        })
      }
    },
    fail: (error) => {
      uni.showToast({
        title: `上传失败：${error.errMsg}`,
        icon: 'none',
      })
    },
  })
}

const uploadChange = (e) => {
  if (
    detectFileTypeS(e[0].tempFilePath) === 'video' ||
    detectFileTypeS(e[0].tempFilePath) === 'audio' ||
    detectFileTypeS(e[0].tempFilePath) === 'archive'
  ) {
    uni.showToast({
      title: '不支持类型',
      icon: 'error',
    })
    imageDefine.value = []
  } else {
    uploadFileToServer(e[0])
  }
}

const passMaximumChange = (value) => {
  uni.showToast({
    title: '选择文件不能超过6个',
  })
}

// 删除文件
const onDelete = (e) => {
  let materialImage = []
  imageDefine.value = imageDefine.value.filter((v) => {
    return v.originalFilename != e.tempFile.name
  })
  imageDefine.value.map((v) => {
    materialImage.push(v.url)
  })
  emit('onDelete', materialImage)
}

// 自定义删除处理
const handleDelete = (file, index) => {
  imageDefine.value.splice(index, 1)
  emit(
    'onDelete',
    imageDefine.value.map((v) => v.url)
  )
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0B'
  const units = ['B', 'KB', 'MB', 'GB']
  let size = bytes
  let unitIndex = 0

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }

  return `${size.toFixed(2)}${units[unitIndex]}`
}

const picker = ref(null)
</script>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.container {
  display: flex;
  padding: 32rpx;
  background-color: #ffffff;
  flex-direction: column;
}

.text {
  display: flex;
  color: #1d2129;
  font-family: 'PingFang SC';
  font-size: 32rpx;
  font-style: normal;
  font-weight: 400;
  line-height: 44.8rpx;
}

:deep(.uni-file-picker__lists-box) {
  left: 0;
}

.file-list {
  margin-top: 20rpx;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;
}

.file-preview {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f5f5;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.is-image image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-icon {
  width: 100%;
  height: 100%;
  line-height: 80rpx;
  text-align: center;
  font-size: 48rpx;
}

.icon-word {
  color: #2d57a9;
}

.icon-pdf {
  color: #e61e24;
}

.icon-excel {
  color: #107c10;
}

.icon-image {
  color: #8e24aa;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  display: inline-block;
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.file-type {
  display: inline-block;
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
  margin-left: 10rpx;
}

.delete-btn {
  margin-left: 20rpx;
  padding: 0;
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
}
</style>
